layui.define(['form', 'http', 'public', 'drawer', 'engine_form'], function (exports) {
    let STR_FORMDESIGN = 'DesignForm';
    let ARR_CONFIG = {
        id: null,            // 当前元素ID
        modeid: 0,
        formid:0,
        data: [],            // 当前元素集合
        state: null,         // 当前活动实例
        index: [],           // 组件分类索引
        itemIndex: {},       // 子组件元素索引
        master: undefined,   // 主界面拖拽实例
        DesignConfig: {},
    };
    let GetSetting = function () {
        return ARR_CONFIG;
    }
    let Init = function () {
        ARR_CONFIG.modeid = layui.public.GetQuery('id') || 0;
        layui.http.SendAjax('/ruinuo/design.form/index', {type:type}, [], function (res) {
            let data = res.data || [];
            data.type=type;
            InitData['source'] = data.source || {};
            ARR_CONFIG.DesignConfig = res.data.config || [];
            layui.public.ViewTpl(data, 'view_body_data', 'view_body');
            layui.public.ViewTpl(data, 'view_mode_list_data', 'view_mode_list');
            let arrs = data.design || [];
            for (let index = 0; index < arrs.length; index++) {
                const element = 'control_' + index;
                const getById = document.getElementById(element);
                ARR_CONFIG.index[element] = new Sortable(getById, {
                    group: {
                        name: STR_FORMDESIGN,
                        pull: 'clone',
                        put: false,
                    },
                    sort: false,
                    animation: 150,
                    onChoose: function (evt) {
                    },  // 拖动前显示
                    onAdd: function (evt) {
                    },     // 添加到这里
                    onEnd: function (evt) {
                    },     // 拖动结束
                });
            }
            let mainContainer = document.getElementById("mainContainer");
            ARR_CONFIG.master = new Sortable(mainContainer, {
                group: {
                    name: STR_FORMDESIGN,
                    pull: true
                },
                handle: '.widget-view-drag',
                dataIdAttr: 'id',
                animation: 150,
                onAdd: function (evt) {
                    addCtrl(evt, 1);
                },
                onUpdate: function (evt) {
                    if (evt.to.id == 'mainContainer') {
                        //[ARR_CONFIG.data[evt.newIndex], ARR_CONFIG.data[evt.oldIndex]] = [ARR_CONFIG.data[evt.oldIndex], ARR_CONFIG.data[evt.newIndex]];
                        let array = ARR_CONFIG.data;
                        let element = array.splice(evt.oldIndex, 1)[0];
                        array.splice(evt.newIndex, 0, element);
                    }
                }
            });
            ModeFind();
        })
    };

    let ModeFind = function (modeid = '') {
        if (modeid) {
            ARR_CONFIG.modeid = modeid;
        }
        let URL='?id='+ARR_CONFIG.modeid+'&type='+type;

        history.pushState(null,null,URL);

        layui.http.SendAjax('/ruinuo/design.form/formfind', {id: ARR_CONFIG.modeid,type:type}, [], function (res) {
            if (res.code != 200) {
                //layer.msg(res.msg, {icon: 2});
                ARR_CONFIG.modeid=0;
                ARR_CONFIG.formfind=0;
                history.pushState(null, null, '?id=0&type='+type);
                return false;
            }
            let form_json = res.data.layout || [];
            let form_label = res.data.label || 'form_top';
            ARR_CONFIG.formid=res.data.id || 0;
            $('#mainContainer').attr('class', form_label);
            let design = ARR_CONFIG['DesignConfig'];
            InitData['source']['database_field'] = res.data.database || {};
            let html = '';
            let Tpl = "<div>" + GetTpl(form_json) + "</div>";
            let ctrlDiv = $(Tpl).get(0);
            let box = -1;
            let that = '';
            form_json.forEach((item, index) => {
                let children = item.children || [];
                box++;
                that = $(ctrlDiv).find('.design-box:eq(' + box + ')');

                $(that).attr("id", item.elem_id);
                $(that).attr("mode", item.tag);
                $(that).addClass("ays-ctrl",);
                if (children.length == 0) {
                    $(that).prepend('<div class="drag_p"></div>');
                }

                children.forEach((item2, index2) => {
                    let children2 = item2.children || [];
                    children2.forEach((item3, index3) => {
                        box++;
                        that = $(ctrlDiv).find('.design-box').eq(box);
                        $(that).attr("id", item3.elem_id);
                        $(that).attr("mode", item3.tag);
                        $(that).addClass("ays-ctrl",);
                        $(that).prepend('<div class="drag_p"></div>');
                    })
                })

            })
            html = $(ctrlDiv).html();
            ARR_CONFIG.data = form_json;
            $('#mainContainer').html(html);
            if (html) {
                BindAciton(form_json);
                $('.design-box').each(function (k) {
                    if (k == 0) {
                        ActiveControl(this);
                        ChangeForm();
                    }
                    activeClickBind(this);
                })
                $('.ays-ctrl-container').each(function () {
                    LoadSortable(this);
                })
            }

            $('.mode_list ul li').each(function () {
                if (ARR_CONFIG.modeid == $(this).attr("data-id")) {
                    let title = $(this).find('.layui-menu-body-title').html();
                    $('.design_head .title').html('表单设计器<i class="layui-icon layui-icon-right"></i><strong style="color: var(--theme_color);">' + title + '</strong>');
                }
            })
        })

    }
    let LoadSortable = function (itemId) {
        let item = new Sortable.create(itemId, {
            group: {
                name: STR_FORMDESIGN,
                pull: true
            },
            handle: '.widget-view-drag',
            dataIdAttr: 'id',
            animation: 150,
            onAdd: function (evt) {
                let mode = $(evt.item).attr('mode');
                if (mode == 'grid' || mode == 'tab' || mode == 'card' || mode == 'flex') {
                    $(evt.item).remove();
                    layer.msg('禁止嵌套', {icon: 2});
                    return false;
                }
                addCtrl(evt, 2);
            },
            onUpdate: function (evt) {
                let myid = $(evt.item.parentElement).attr('id');
                let ids = myid.split('_s_');
                let parentId = ids[0];
                let parentIndex = ids[1];
                let gridElem = recursiveFindElem(ARR_CONFIG.data, parentId);
                let children = gridElem.children[parentIndex].children;
                let element = children.splice(evt.oldIndex, 1)[0];
                children.splice(evt.newIndex, 0, element);
            },
        });

        ARR_CONFIG.itemIndex[itemId] = item;
    }

    let addCtrl = function (evt, type = 1) {
        let modeid = ARR_CONFIG.modeid || 0;
        if (modeid == 0) {
            $(evt.item).remove();
            layer.msg('请先选择模块', {icon: 2});
            layui.public.DrawerTpl('.mode_list', '300px', '模块类别');
            return false;
        }
        let item = evt.item;
        let mode = item.getAttribute("mode") || '';
        if (mode) {
            let newElem = GetHtml(mode, type, evt);
            item.parentNode.replaceChild(newElem, item);
            let containers = $(newElem).find('.ays-ctrl-container');
            for (let i = 0; i < containers.length; i++) {
                LoadSortable(containers[i]);
            }
            layui.form.render();
        }
    }

    let GetHtml = function (mode = '', type = 1, evt) {
        let myid = $(evt.item).attr('id') || '';
        let item=[];
        if (myid == "") {
            let copyArr = $.extend(true, [], ARR_CONFIG['DesignConfig']);
            item = copyArr[mode];
        } else {
            item = ChangeForm(1);
        }

        GetForm(item, mode);
        let current = {};
        for (let i = 0; i < item.length; i++) {
            let res = item[i];
            current['tag'] = mode;
            current[res['field']] = res['value'] || '';
        }
        let id = GetId();
        current['elem_id'] = id;
        if (mode == 'card' || mode == 'flex') {
            current['children'] = [{children: []}];
        }


        let Tpl = GetTpl([current]);
        let ctrlDiv = $(Tpl).get(0);
        $(ctrlDiv).attr("id", id);
        $(ctrlDiv).attr("mode", mode);
        activeClickBind(ctrlDiv);
        ActiveControl(ctrlDiv);
        switch (type) {
            case 1:
                if (myid) {
                    current = JSON.parse(JSON.stringify(recursiveFindElem(ARR_CONFIG.data, myid)));
                    recursiveDelete(ARR_CONFIG.data, myid);
                }
                current['elem_id'] = id;
                ARR_CONFIG.data.splice(evt.newIndex, 0, current);
                break;
            case 2:
                let toid = evt.to.id;
                let ids = toid.split('_s_');
                let parentId = ids[0];
                let parentIndex = ids[1];
                let gridElem = recursiveFindElem(ARR_CONFIG.data, parentId);
                if (myid) {
                    current = JSON.parse(JSON.stringify(recursiveFindElem(ARR_CONFIG.data, myid)));
                    current['elem_id'] = id;
                    gridElem.children[parentIndex].children.splice(evt.newIndex, 0, current);
                    recursiveDelete(ARR_CONFIG.data, myid);
                } else {
                    gridElem.children[parentIndex].children.splice(evt.newIndex, 0, current);
                }
                break;
        }
        return ctrlDiv;
    }

    let activeClickBind = function (elem) {
        $(elem).click(function (event) {
            if ($(ARR_CONFIG.state).attr('id') != $(this).attr('id')) {
                ActiveControl(this);
                ChangeForm();
            }
            if ($(ARR_CONFIG.state).attr('mode') != "tab") {
                stopBubbling(event);
            }
        })
    }
    let stopBubbling = function (e) {
        e = window.event || e;
        if (e.stopPropagation) {
            e.stopPropagation(); //阻止事件 冒泡传播
        } else {
            e.cancelBubble = true; //ie兼容
        }
    }

    let ActiveControl = function (elem) {
        elem = $(elem);
        let activeContainer = ARR_CONFIG.state;
        if (activeContainer != null) {
            activeContainer.children('.widget-view-drag').remove();
            activeContainer.children('.widget-view-action').remove();
            activeContainer.removeClass('widget-view-ctrl-action');
            activeContainer.addClass('ays-ctrl');
        }
        ARR_CONFIG.state = elem;
        ARR_CONFIG.id = $(elem).attr("id");
        activeContainer = elem;
        activeContainer.addClass('widget-view-ctrl-action');
        activeContainer.removeClass('ays-ctrl');
        if (activeContainer.find(".widget-view-drag").length == 0) {
            let widgetViewDrag = $(
                '<div title="拖动"><i class="layui-icon layui-icon-slider"></i></div>');
            widgetViewDrag.addClass('widget-view-drag');
            activeContainer.prepend(widgetViewDrag);
        }

        if (activeContainer.find(".drag_p").length == 0 && activeContainer.find(".ays-ctrl-container").length == 0) {
            let widgetViewDrag = $('<div class="drag_p"></div>');
            activeContainer.prepend(widgetViewDrag);
        }
        if (activeContainer.find(".widget-view-action").length == 0) {
            let widgetViewAction = $('<div></div>');
            widgetViewAction.addClass('widget-view-action');
            let widgetViewActionDeleteBtn = $('<div class="delete" title="删除"><i class="layui-icon layui-icon-delete"></i></div>');
            widgetViewActionDeleteBtn.click(function () {
                layer.confirm('确定要删除吗', {icon: 3}, function (index) {
                    layer.close(index);
                    recursiveDelete(ARR_CONFIG.data, ARR_CONFIG.id);
                    elem.remove();
                    ARR_CONFIG.id = null;
                    ARR_CONFIG.state = null;
                    $(".design-right-con").html("");
                });
            })
            widgetViewAction.append(widgetViewActionDeleteBtn);
            activeContainer.prepend(widgetViewAction);
        }
    }

    /*更新组件*/
    let UpJson = function () {
        let id = $(".widget-view-ctrl-action").attr("id");
        let json = recursiveFindElem(ARR_CONFIG.data, id);
        console.log(json);
        let copyArr = $.extend(true, [], ARR_CONFIG['DesignConfig']);
        let field = copyArr[json['tag']];
        let FormData = {};
        field.forEach(item => {
            FormData[item.field] = item.value || '';
        })
        let data = layui.engine_form.GetFormData(FormData, '.design-right ');
        let old_col = json['col'] || 12;
        let new_col = data['col'] || 12;
        $("#" + id).removeClass("layui-col-md" + old_col);
        $("#" + id).addClass("layui-col-md" + new_col);
        for (const key in json) {
            json[key] = data[key] || json[key];
            if (data.hasOwnProperty(key)) {
                json[key] = data[key] || '';
            }
            if (key == 'children' || key == 'cols' || key == 'event_val' || key == 'num_rule') {
                try {
                    json[key] = JSON.parse(json[key]);
                } catch (err) {
                    console.log(err);
                }
            }
        }
        let Tpl = GetTpl([json]);
        let ctrlDiv = $(Tpl).get(0);
        $("#" + id).html($(ctrlDiv).html());
        let containers = $(".ays-ctrl-container");
        for (let i = 0; i < containers.length; i++) {
            LoadSortable(containers[i]);
        }
        let arr = json['children'] || [];
        for (let i = 0; i < arr.length; i++) {
            let list = arr[i]['children'] || [];
            for (let ii = 0; ii < list.length; ii++) {
                let elem_id = list[ii].elem_id;
                let tag = list[ii].tag;
                let box = $('#focus_' + elem_id).parent('.layui-input-block').parent('.design-box');
                $(box).attr("id", elem_id);
                $(box).attr("mode", tag);
                $(box).addClass('ays-ctrl');
                $(box).prepend('<div class="drag_p"></div>');
                activeClickBind($("#" + elem_id));
            }
        }
        activeClickBind($("#" + id));
        ActiveControl($("#" + id));
        InputOn(2);
    }

    /*点击切换表单*/
    let ChangeForm = function (type = '') {
        let id = $(".widget-view-ctrl-action").attr("id");
        let json = recursiveFindElem(ARR_CONFIG.data, id);
        let copyArr = $.extend(true, [], ARR_CONFIG['DesignConfig']);
        let rows = copyArr[json['tag']];
        for (let i = 0; i < rows.length; i++) {
            let field = rows[i].field || '';
            if (field) {
                rows[i].value = json[field];
            }
        }
        if (type) {
            return rows;
        }
        GetForm(rows, json['tag']);
    }


    let InputOn = function (type = 1) {
        if (type == 1) {
            $('.design-right input,.design-right textarea').on('change', function () {
                let length = $(this).parent('.layui-table-cell').length;
                if (length == 0) {
                    UpJson();
                }
            });
        }
        let id = $(".widget-view-ctrl-action").attr("id");
        let json = recursiveFindElem(ARR_CONFIG.data, id);
        BindAciton([json]);
        layui.form.render();
        ShowTagName();
    }

    let GetId = function () {
        return (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString()
            .substr(2, 5);
    }


// 查找原始元素
    let recursiveFindElem = function (array, elem_id) {
        let that = this;
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            if (element.elem_id == elem_id) {
                return element;
            }
            if (typeof element.children != 'undefined'
                && element.children.length) {
                let subElem = element.children;
                for (let i = 0; i < subElem.length; i++) {
                    if (subElem[i].children.length) {
                        let item = recursiveFindElem(subElem[i].children, elem_id);
                        if (item && typeof item != 'undefined') {
                            return item;
                        }
                    }
                }
            }
        }
    }
    // 删除原始元素
    let recursiveDelete = function (array, elem_id) {
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            if (element.elem_id == elem_id) {
                array.splice(index, 1);
                break;
            }
            if (typeof element.children != 'undefined'
                && element.children.length) {
                let subElem = element.children;
                for (let i = 0; i < subElem.length; i++) {
                    if (subElem[i].children.length) {
                        recursiveDelete(subElem[i].children, elem_id);
                    }
                }
            }
        }
    }
    let SaveSubmit = function (v_type = 1) {
        let rows = ARR_CONFIG.data || [];
        if (rows.length == 0) {
            layui.layer.msg('请先设计表单', {icon: 2});
            return false;
        }
        let msg = '';
        let elem_id = '';
        rows.forEach(item => {
            let children = item.children || [];
            if (item.hasOwnProperty('field')) {
                if (msg == '' && item.field == '') {
                    msg = item.tag + '组件需要选择字段';
                    elem_id = item.elem_id;
                }
            }
            children.forEach(item2 => {
                let children2 = item2.children || [];
                children2.forEach(item3 => {
                    if (item3.hasOwnProperty('field')) {
                        if (msg == '' && item3.field == '') {
                            msg = item3.tag + '组件需要选择字段';
                            elem_id = item3.elem_id;
                        }
                    }
                })
            })
        })
        if (msg) {
            ActiveControl($('#' + elem_id));
            ChangeForm();
            layui.layer.msg(msg, {icon: 2});
            return false;
        }
        if (v_type == 2) {
            ViewBrowse();
            return false;
        }


        let form = {
            id: ARR_CONFIG.modeid,
            type:type,
            layout: JSON.stringify(rows),
        }
        layui.http.SendAjax('/ruinuo/design.form/uplayout', form, [], function (res) {
            if (res.code != 200) {
                layui.layer.msg(res.msg, {icon: 2});
                return false;
            }
            layui.layer.msg('保存成功', {icon: 1});
        })
    }
    let QieHuan = function (type = 1) {

        $(".design_button ul li").removeClass("on");
        if (type == 1) {
            $("#mainContainer").css("width", "auto");
            $(".design_button ul li:eq(0)").addClass("on");
        }
        if (type == 2) {
            $("#mainContainer").css("width", "750px");
            $(".design_button ul li:eq(1)").addClass("on");
        }
        if (type == 3) {
            $("#mainContainer").css("width", "375px");
            $(".design_button ul li:eq(2)").addClass("on");
        }
    }
    let FormSetting = function () {
        let formid = ARR_CONFIG.formid || 0;
        if (formid!=0) {
            let url='/ruinuo/form/edit/?id=' + formid;
            if (type==2)
            {
                url='/ruinuo/setting/edit/?id=' + formid;
            }
            eventForm=1;
            layui.public.OpenWindow(url, '表单配置');
        } else {
            layui.layer.msg('请先选择模块', {icon: 2});
            layui.public.DrawerTpl('.mode_list', '300px', '模块类别');
        }
    }

    let GetTpl = function (current) {
        let bHtml = '';
        let htmlData = {detail: {}, source: InitData.source}
        current.forEach((val, index) => {
            if (val.hasOwnProperty('field')) {
                let eid = 'falsefield_' + val['elem_id'];
                let field = val['field'] || eid;
                htmlData['detail'][field] = '';
                current[index]['field'] = field;

            }
        });
        layui.http.SendAjax('/ruinuo/design.form/form', {
            layout: JSON.stringify(current),
            async: 1
        }, [], function (res) {
            let source = res.data.source || {};
            $.each(source, function (tk, tv) {
                htmlData['source'][tk] = tv;
            })
            layui.laytpl(res.data.html).render(htmlData, function (html) {
                bHtml = html;
            });

        })
        current.forEach((val, index) => {
            if (val.hasOwnProperty('field')) {
                let eid = 'falsefield_' + val['elem_id'];
                if (val['field'] == eid) {
                    current[index]['field'] = '';
                }
            }
        });
        InitData=htmlData;
        return bHtml;
    }

    let GetForm = function (item = [], tag = '') {
        item.forEach(val => {
            val['elem_id'] = val['elem_id'] || GetId();
        })
        let data = {
            layout: JSON.stringify(item),
        };
        if (tag == 'qrcode' || 'barcode') {
            InitData['source']['code_field']['rows'] = GetFieldData(3);
        }
        InitData['detail'] = {};
        layui.http.SendAjax('/ruinuo/design.form/form', data, [], function (res) {
            let copyArr = $.extend(true, [], item);
            copyArr.forEach(val => {
                let vv = val['value'] || '';
                if ((val['field'] == 'children' && (tag == 'tab' || tag == 'grid')) || val['field'] == 'cols' || val['field'] == 'event_val' || val['field'] == 'num_rule') {
                    if (vv) {
                        vv = JSON.stringify(vv);
                    }
                }
                InitData['detail'][val['field']] = vv;
            })
            let html = res.data.html;
            switch (tag) {
                case "jsontable":
                case "subtable":
                case "choosetable":
                    html += '<div class="layui-col-xs12 layui-col-md12" style="margin-top: 15px">' +
                        '<button type="button" class="layui-btn layui-btn-fluid" onclick="layui.design_form.OpenCols(\'' + tag + '\')">显示配置</button>' +
                        '</div>'
                    break;
                case "gongshi":
                    html += '<div class="layui-col-xs12 layui-col-md12" style="margin-top: 15px">' +
                        '<button type="button" class="layui-btn layui-btn-fluid" onclick="layui.design_form.OpenCols(\'' + tag + '\')">公式配置</button>' +
                        '</div>'
                    break;
                case "radio":
                case "select":
                    html += '<div class="layui-col-xs12 layui-col-md12" style="margin-top: 15px">' +
                        '<button type="button" class="layui-btn layui-btn-fluid" onclick="layui.design_form.OpenCols(\'' + tag + '\')">事件配置</button>' +
                        '</div>'
                    break;
                case "ordernum":
                case "openselect":
                    html += '<div class="layui-col-xs12 layui-col-md12" style="margin-top: 15px">' +
                        '<button type="button" class="layui-btn layui-btn-fluid" onclick="layui.design_form.OpenCols(\'' + tag + '\')">关联配置</button>' +
                        '</div>'
                    break;
            }
            $("#design-right-con-data").html(html);
            layui.public.ViewTpl(InitData, 'design-right-con-data', 'design-right-con');
            $(".design-right-con .options_num_box .layui-form-label").append('<span class="layui-btn layui-btn-sm btn_theme_1" onclick="layui.design_form.OptionsAciton();" style="float: right"><i class="ruinuo-icon icon-add-bold"></i></span>')
            BindAciton(item);
            CheckboxAction();
            RadioAction();
            SelectAction();
            SwitchAction();
            InputOn();
            FieldsDisabled();
        })
    }

    let OptionsAciton=function ()
    {
        eventForm=2;
        layui.public.OpenWindow('/admin/options/add/','添加数据源',700,0);
    }

    let BindAciton = function (arr = []) {
        layui.element.init();
        arr.forEach(item => {
            let tag = item.tag;
            let elem_id = item.elem_id || '';
            let field = item.field || '';
            let height = item.height || 400;
            /*循环绑定事件*/
            let children = item.children || [];
            for (let ii = 0; ii < children.length; ii++) {
                let items = children[ii]['children'] || [];
                if (items.length != 0) {
                    BindAciton(items);
                }
            }
            switch (tag) {
                case "showtree":
                    let options_num = item.options_num || '';
                    options_num = options_num.split('|');
                    layui.engine_form.BindShowTree(elem_id, field,options_num[0])
                    break;
                case "datetime":
                    let type = item.date_cat || 'date';
                    let range = item.range || false;
                    let range_field = item.range_field || '';
                    layui.engine_form.BindDateTime(elem_id, type, range, field, range_field);
                    break;
                case "dateall":
                    layui.engine_form.BindDateAll(elem_id, field);
                    break;
                case "color":
                    layui.engine_form.BindColor(elem_id);
                    break;
                case "slider":
                    let min_val = item.min_val || 1;
                    let max_val = item.max_val || 100;
                    layui.engine_form.BindSlider(elem_id, min_val, max_val);
                    break;
                case "rate":
                    layui.engine_form.BindRate(elem_id);
                    break;
                case "htmledit":
                    layui.engine_form.BindHtmlEdit(elem_id, height);
                    break;
                case "markdown":
                    layui.engine_form.BindMarkDown(elem_id, height);
                    break;
                case "icon":
                    layui.engine_form.BindIcon(elem_id);
                    break;
                case "openselect":
                    layui.engine_form.BindOpenSelect(elem_id);
                    break;
                case "select":
                case "cascader":
                case "tree":
                    let is_all = item.is_all || 2;
                    if (tag == 'select' && is_all == 2) {
                    } else {
                        let strict = item.strict || false;
                        let options_num = item.options_num || '';
                        options_num = options_num.split('|');
                        layui.engine_form.BindSelect(elem_id, tag, field, options_num[0], is_all, strict);
                    }
                    break;
                case "upimg":
                case "upfile":
                    let cat = item.cat || '';
                    let size = item.size || '';
                    let num = item.num || 1;
                    let file = item.file || '';
                    layui.engine_form.BindUpload(elem_id, file, tag, cat, size, num);
                    break;
                case "tags":
                    let placeholder = item.placeholder || '回车确定';
                    layui.engine_form.BindTags(elem_id, placeholder);
                    break;
                case "qrcode":
                case "barcode":
                    let code_field = item.code_field || elem_id;
                    layui.engine_form.BindCode(elem_id, code_field);
                    break;
                case "jsontable":
                case "subtable":
                case "choosetable":
                    let copyArr = $.extend(true, [], item);
                    copyArr.cols = eval(copyArr.cols) || [];
                    copyArr.cols.forEach(item=>{
                        item.minWidth=item.width || 160;
                        delete (item.width) ;
                    })
                    layui.engine_form.BindJsonTable(copyArr);
                    break;
            }
        })
    }

    let FieldsDisabled = function () {
        let fields = GetFieldData(2);
        let obj = $(".design-right-con").find("select[name='field']");
        let val = $(obj).val();
        $(obj).find('option').each(function () {
            let option_val = $(this).val();
            if (fields.indexOf('(' + option_val + ')') >= 0 && option_val && option_val != val) {
                $(this).attr("disabled", true);
            }
        })
        layui.form.render();
    }

    let GetFieldData = function (type = 1) {
        let FieldData = [];
        let field = '';
        let rows = ARR_CONFIG.data || [];
        let CodeFiled = [];
        rows.forEach(item => {
            let children = item.children || [];
            if (item.hasOwnProperty('field') && !children.length) {
                if (item.field) {
                    FieldData.push(item);
                    field += '(' + item.field + ')';
                    CodeFiled.push({label: item.title + '_' + item.field, value: item.field})
                }
            }
            children.forEach(item2 => {
                let children2 = item2.children || [];
                children2.forEach(item3 => {
                    if (item3.hasOwnProperty('field')) {
                        if (item3.field) {
                            FieldData.push(item3);
                            field += '(' + item3.field + ')';
                            CodeFiled.push({label: item3.title + '_' + item3.field, value: item3.field})

                        }
                    }
                })
            })
        })
        if (type == 2) {
            return field;
        }
        if (type == 3) {
            return CodeFiled;
        }

        return FieldData;
    }
    let OpenCols = function (tag) {
        let area = ['90%', '90%'];
        let content = '';
        let that = '';
        switch (tag) {
            case "jsontable":
                let database=$(".design-right-con select[name='database']").val() || '';
                let database_field=$(".design-right-con input[name='database_field']").val() || '';
                if (database && database_field=='')
                {
                    $(".design-right-con input[name='database_field']").focus();
                    $(".design-right-con input[name='database_field']").addClass('layui-form-danger');
                    layui.layer.msg('请填写子表关联字段', {icon: 2});
                    return false;
                }
                content = '/common/component/jsontable/?database='+database;
                that = $(".design-right-con textarea[name='cols']");
                break;
            case "subtable":
                let mode_id=$(".design-right-con select[name='mode_id']").val() || '';
                if (mode_id=="")
                {
                    $(".design-right-con select[name='mode_id']").focus();
                    $(".design-right-con select[name='mode_id']").addClass('layui-form-danger');
                    layui.layer.msg('请先选择模型', {icon: 2});
                    return false;
                }
                let mode_sub_id=$(".design-right-con input[name='mode_sub_id']").val() || '';
                if (mode_sub_id=="")
                {
                    $(".design-right-con input[name='mode_sub_id']").focus();
                    $(".design-right-con input[name='mode_sub_id']").addClass('layui-form-danger');
                    layui.layer.msg('请先填写关联ID', {icon: 2});
                    return false;
                }
                content = '/common/component/subtable';
                that = $(".design-right-con textarea[name='cols']");
                break;

            case "choosetable":
                let mode_idt=$(".design-right-con select[name='mode_id']").val() || '';
                if (mode_idt=="")
                {
                    $(".design-right-con select[name='mode_id']").focus();
                    $(".design-right-con select[name='mode_id']").addClass('layui-form-danger');
                    layui.layer.msg('请先选择模型', {icon: 2});
                    return false;
                }
                content = '/common/component/choosetable';
                that = $(".design-right-con textarea[name='cols']");
                break;
            case "gongshi":
                content = '/common/component/gongshi';
                that = $(".design-right-con input[name='gongshi_txt']");
                area = ['500px', '500px'];
                break;
            case "radio":
            case "select":
            case "checkbox":
                content = '/common/component/bindevent';
                that = $(".design-right-con textarea[name='event_val']");
                break;
            case "ordernum":
                content = '/common/component/numrule';
                that = $(".design-right-con textarea[name='num_rule']");
                break;
            case "openselect":
                content = '/common/component/openselect';
                that = $(".design-right-con textarea[name='event_val']");
                break;
        }
        layer.open({
            type: 2,
            offset: 'auto',
            title: '配置',
            area: area,
            scrollbar: true,
            content: content,
            btnAlign: 'r',
            btn: ['确定', '取消'],
            shade: 0.3,
            yes: function (index) {
                let iframe = window['layui-layer-iframe' + index];
                let backdata = iframe.SendForm() || false;
                if (backdata == false) {
                    return false;
                }
                $(that).val(backdata);
                let bindex = layer.getFrameIndex('layui-layer-iframe' + index);
                layer.close(bindex);
                UpJson();
            }
        })
    }
    let ViewBrowse = function () {
        layui.public.OpenWindow('/ruinuo/design.form/browse/', '预览');
    }
    let ShowTagName=function ()
    {
        $("#mainContainer").find(".design-box").each(function (k) {
            let mode=$(this).attr("mode");
            let drag_p_length=$(this).find(".drag_p").length;
            let tag_name_length=$(this).find(".tag_name").length;
            if (drag_p_length==1 && tag_name_length==0 && mode!='tips' && mode!='legend')
            {
                let icon=$(".components-list").find('*[mode="'+mode+'"]').find('i').attr("class");
                let text=$(".components-list").find('*[mode="'+mode+'"]').find('span').text();
                $(this).find(".layui-form-label").append('<div class="tag_name" title="'+text+'"><i class="'+icon+'"></i></div>');
            }
        })

    }


    let design_form = {
        Init: Init,//初始化
        addCtrl: addCtrl,//拖曳完成
        LoadSortable: LoadSortable,//布局拖拽
        GetId: GetId,//唯一ID
        GetHtml: GetHtml,//获取html
        activeClickBind: activeClickBind,//获取html
        ActiveControl: ActiveControl,//获取html
        stopBubbling: stopBubbling,//获取html
        UpJson: UpJson,
        ChangeForm: ChangeForm,
        InputOn: InputOn,
        recursiveDelete: recursiveDelete,
        recursiveFindElem: recursiveFindElem,
        SaveSubmit: SaveSubmit,
        QieHuan: QieHuan,
        ModeFind: ModeFind,
        FormSetting: FormSetting,
        GetTpl: GetTpl,
        GetForm: GetForm,
        BindAciton: BindAciton,
        FieldsDisabled: FieldsDisabled,
        GetFieldData: GetFieldData,
        OpenCols: OpenCols,
        GetSetting: GetSetting,
        ViewBrowse: ViewBrowse,
        OptionsAciton:OptionsAciton,
        ShowTagName:ShowTagName,
    };
    exports('design_form', design_form);
})



